package eu.chargetime.ocpp.jsonclientimplementation.connect;

import com.google.gson.Gson;
import eu.chargetime.ocpp.JSONClient;
import eu.chargetime.ocpp.OccurenceConstraintException;
import eu.chargetime.ocpp.UnsupportedFeatureException;
import eu.chargetime.ocpp.feature.profile.ClientCoreProfile;
import eu.chargetime.ocpp.jsonclientimplementation.config.ApiConfigurations;
import eu.chargetime.ocpp.model.core.AuthorizationStatus;
import eu.chargetime.ocpp.model.core.AuthorizeConfirmation;
import eu.chargetime.ocpp.model.core.AuthorizeRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;
import java.util.concurrent.ExecutionException;

/**
 * @author zhaorui
 * @Date 2024/4/20  16:20
 * @description: 初始化连接到 Server 端
 */
@Slf4j
public class InitServer {

    @Autowired
    private JSONClient jsonClient;

    @Autowired
    private ClientCoreProfile clientCoreProfile;

    @Autowired
    private ApiConfigurations apiConfigurations;

    public void testOCPPAuthorizeHandler() {
        Gson gson = new Gson();
        String url = "ws://" + apiConfigurations.getWebSocketBaseUrl();
        AuthorizeRequest testRequest = clientCoreProfile.createAuthorizeRequest("testId");
        jsonClient.connect(url, null);
        try {
            AuthorizeConfirmation authorizeConfirmation = (AuthorizeConfirmation) jsonClient.send(testRequest)
                    .toCompletableFuture().get();

            log.info("[authorizeConfirmation],authorizeConfirmation");

            if (Objects.equals(AuthorizationStatus.Accepted, authorizeConfirmation.getIdTagInfo().getStatus())) {
                log.info("[会话建立成功],");
                Thread.sleep(50000);
            }


        } catch (OccurenceConstraintException | UnsupportedFeatureException
                 | ExecutionException | InterruptedException e) {
            log.error("Exception occurred: " + e);
            log.error("Test will fail");
        }
    }


}
